﻿@namespace Project.Web.Shared.Components
@typeparam TModel
@{
    int childIndex = 0;
}
<div style="padding:5px;">
    @if (Index > 0)
    {
        <div style="margin-bottom:10px;">
            @(UI.BuildRadioGroup<Options<LinkType>, LinkType>(this, Root.LinkOptions)
                .LabelExpression(p => p.Label)
                .ValueExpression(p => p.Value)
                .Bind(() => Item.LinkType)
                .Set(p => p.ButtonGroup, true)
                .Render())
        </div>
    }
    <StackPanel>
        @(UI.BuildSelect<ColumnInfo, string>(this, Columns)
            .ValueExpression(c => c.PropertyOrFieldName)
            .LabelExpression(c => Localizer[c.Label])
            .Bind(() => Item.Name!)
            .Style("min-width:150px;")
            .Render()
        )
        @(UI.BuildSelect<CompareType>(this, null)
            .Bind(() => Item.CompareType)
            .Style("width:80px;")
            .Render())
        @ValueInput()
        @if (Index == 0)
        {
            @UI.BuildButton(this).Text(TableLocalizer["AdvanceCondition.AddCondition"]).Primary().OnClick(AddSibling).Render()
        }
        @UI.BuildButton(this).Text(TableLocalizer["AdvanceCondition.AddChildCondition"]).Primary().OnClick(AddChild).Render()
        @UI.BuildButton(this).Text(TableLocalizer["AdvanceCondition.RemoveCondition"]).SetButtonType(ButtonType.Danger).OnClick(Remove).Render()
    </StackPanel>

    @if (Item.Children.Count > 0)
    {
        <div class="children-wrapper">
            <div style=@($"padding:8px 0;margin-left:{Indent}px;")>
                @(UI.BuildRadioGroup<Options<LinkType>, LinkType>(this, Root.LinkOptions)
                    .LabelExpression(p => p.Label)
                    .ValueExpression(p => p.Value)
                    .Bind(() => Item.LinkChildren)
                    .Set(p => p.ButtonGroup, true)
                    .Render())
            @UI.BuildButton(this).Text(TableLocalizer["AdvanceCondition.RemoveCondition"]).Primary().SetButtonType(ButtonType.Danger).OnClick(RemoveChildren).Render()
            </div>
            <div style=@($"border:1px solid #ccc; padding: 8px {Indent}px; margin-left:{Indent}px;")>
                @foreach (var item in Item.Children)
                {
                    <Group Item="item"
                           Columns="Columns"
                           UI="UI"
                           Indent="@Indent"
                           Index="childIndex"
                           Parent="Item"
                           TModel="TModel"></Group>
                    childIndex++;
                }
            </div>
        </div>
    }
</div>

@code {
    [Parameter, NotNull] public ConditionUnit? Item { get; set; }
    [Parameter, NotNull] public ConditionUnit? Parent { get; set; }
    [Parameter, NotNull] public ColumnInfo[]? Columns { get; set; }
    [Parameter, NotNull] public IUIService? UI { get; set; }
    [CascadingParameter(Name = nameof(Localizer)), NotNull] public IStringLocalizer? Localizer { get; set; }
    [CascadingParameter(Name = nameof(TableLocalizer)), NotNull] public IStringLocalizer? TableLocalizer { get; set; }
    [CascadingParameter, NotNull] public ConditionBuilder<TModel>? Root { get; set; }
    [Parameter] public int Index { get; set; }
    [Parameter] public int Indent { get; set; }
    protected override void OnInitialized()
    {
        base.OnInitialized();
        if (Index == 0)
        {
            Item.LinkType = LinkType.None;
        }
    }
    public Task AddChild()
    {
        Item.Children.Add(new());
        // return InvokeAsync(StateHasChanged);
        return Task.CompletedTask;
    }
    public Task AddSibling()
    {
        Parent.Children.Add(new());
        return Root.UpdateView();
    }

    public Task Remove()
    {
        Parent.Children.Remove(Item);
        return Root.UpdateView();
    }

    public Task RemoveChildren()
    {
        Item.Children.Clear();
        return Task.CompletedTask;
    }

    DateTime? dateValue = null;
    string? stringValue = string.Empty;
    Func<object?>? GetCurrentValue;
    RenderFragment ValueInput()
    {
        ColumnInfo? selectedField = Columns.FirstOrDefault(c => c.PropertyOrFieldName == Item.Name);

        if (selectedField?.DataType == typeof(DateTime) || selectedField?.DataType == typeof(DateTime?))
        {
            GetCurrentValue = () => dateValue;
            return UI.BuildDatePicker(this)
                .Bind(() => dateValue, NotifyChanged)
                .Style("width:200px;")
                .Render();
        }
        else if (selectedField?.EnumValues != null || (selectedField?.IsEnum ?? false))
        {
            GetCurrentValue = () => stringValue;
            return UI.BuildSelect<KeyValuePair<string, string>, string>(this, selectedField.EnumValues!.ToList())
                .LabelExpression(kv => kv.Value)
                .ValueExpression(kv => kv.Key)
                .Bind(() => stringValue!, NotifyChanged)
                .Style("width:200px;")
                .Render();
        }
        else
        {
            GetCurrentValue = () => stringValue;
            return UI.BuildInput(this)
                .Bind(() => stringValue!, NotifyChanged)
                .Style("width:200px;")
                .Render();
        }
    }

    Task NotifyChanged()
    {
        Item.Value = GetCurrentValue?.Invoke();
        return Task.CompletedTask;
    }
}
